package com.examination.mlib.customview.surface;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.android.arouter.launcher.ARouter;
import com.examination.mlib.R;
import com.examination.mlib.constants.ARouterConstants;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by SHICHENG
 * <p>
 * Time on 2022/01/10
 */
public class SurfaceVideo extends FrameLayout
implements MediaPlayer.OnCompletionListener, MediaPlayer.OnVideoSizeChangedListener, MediaPlayer.OnPreparedListener, SeekBar.OnSeekBarChangeListener, MediaPlayer.OnErrorListener{

    private SurfaceView guideVdSv;
    private LinearLayout guideVdContinue;
    private ImageView guideVdStart;
    private LinearLayout guideVdProgressLl;
    private TextView guideVdProgressTime;
    private SeekBar guideVdProgressSeek;
    private TextView guideVdProgressEndTime;
    private Button guideVdProgressMax;
    private ImageView loadingImg;
    private LinearLayout guideVdLl;
    private RelativeLayout guideSvRl;
    private RelativeLayout guideVdRl;

    private Timer timer;
    private TimerTask task;

    private MediaPlayer mediaPlayer;
    private SurfaceHolder surfaceHolder;
    private int p = 0;
    private String videoUrl;
    private Handler handler;
    AnimationDrawable animationDrawable;
    boolean isCompletion = false;
    ConnectivityManager connectivityManager;
    public SurfaceVideo(Context context) {
        super(context);
        initView(context);
    }

    public SurfaceVideo(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public SurfaceVideo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    void initView(Context context){
        connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        handler = new Handler();
        LayoutInflater.from(context).inflate(R.layout.custome_layout_surface,this);
        guideVdRl = (RelativeLayout) findViewById(R.id.guide_vd_rl);
        guideVdSv =  findViewById(R.id.guide_vd_sv);
        guideSvRl = findViewById(R.id.rlayout_video);
        guideVdLl = (LinearLayout) findViewById(R.id.guide_vd_ll);
        guideVdContinue =  findViewById(R.id.guide_vd_continue);
        guideVdStart =  findViewById(R.id.guide_vd_start);
        guideVdProgressLl =  findViewById(R.id.guide_vd_progress_ll);
        guideVdProgressTime =  findViewById(R.id.guide_vd_progress_time);
        guideVdProgressSeek =  findViewById(R.id.guide_vd_progress_seek);
        guideVdProgressEndTime =  findViewById(R.id.guide_vd_progress_end_time);
        guideVdProgressMax =  findViewById(R.id.guide_vd_progress_max);

        loadingImg = findViewById(R.id.guide_loading);
        setListener(context);
    }

    void setListener(Context context){

        ClickUtils.setFastOnClickListener(guideVdProgressMax, v -> {
            int currentPosition = mediaPlayer.getCurrentPosition();
            ARouter.getInstance().build(ARouterConstants.VideoPlayerFullActivity)
                    .withInt("currentPosition",currentPosition)
                    .withString("url",videoUrl)
                    .navigation((Activity) context,2001);
            mediaPlayer.pause();
        });


        //播放点击
        ClickUtils.setFastOnClickListener(guideVdStart, v -> {
            if (mediaPlayer!=null){
                if (mediaPlayer.isPlaying()){
                    mediaPlayer.pause();
                    isPlayer(false);
                }else{
                    mediaPlayer.start();
                    isPlayer(true);
                }
            }
        });

        //继续播放点击
        ClickUtils.setFastOnClickListener(guideVdContinue, new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer!=null){
                    if (!mediaPlayer.isPlaying()){
                        mediaPlayer.start();
                        isPlayer(true);
                    }else{
                        ALog.e(this.getClass().getSimpleName(),"mediaplayer is not stop");
                    }
                }else{
                    ALog.e(this.getClass().getSimpleName(),"mediaplayer is null");
                }
            }
        });

        //点击视频显示进度条
        ClickUtils.setFastOnClickListener(guideVdSv, v -> {
            if (loadingImg.getVisibility() == VISIBLE){
                return;
            }
            if (guideVdProgressLl.getVisibility() == GONE){
                //显示Progress
                guideVdProgressLl.setVisibility(VISIBLE);
                if (isWifi()){
                    guideVdStart.setVisibility(VISIBLE);
                }else{
                    if (mediaPlayer!=null && mediaPlayer.isPlaying()){
                        guideVdStart.setVisibility(VISIBLE);
                    }
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable,1500);
            }else{
                //隐藏Progress
                guideVdProgressLl.setVisibility(GONE);
                guideVdStart.setVisibility(GONE);
            }
        });



    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        isCompletion = true;
        isPlayer(false);
    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        loading(false);
        return false;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onPrepared(MediaPlayer mp) {
        loading(false);
        mp.seekTo(p);//开始时是从0开始播放，恢复时是从指定位置开始播放
        guideVdProgressSeek.setMax(mp.getDuration());//将进度条的最大值设为文件的总时长
        guideVdProgressTime.setText("00:00");
        guideVdProgressEndTime.setText(String.valueOf(msConvertToMinute(mp.getDuration())));
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                guideVdProgressSeek.setProgress(mp.getCurrentPosition());//将媒体播放器当前播放的位置赋值给进度条的进度
                //tv_currentprogress.setText("00:05");
            }
        };
        timer.schedule(task, 0, 100);
        if (p>0){
            mp.start();
            isPlayer(true);
        }else{
//            isPlayer(false);
            guideVdProgressLl.setVisibility(VISIBLE);
            guideVdStart.setVisibility(VISIBLE);
            guideVdLl.setVisibility(GONE);
        }
//        timer.schedule(task, 0, 100);
        loading(false);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        guideVdProgressTime.setText(String.valueOf(msConvertToMinute(progress)));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        mediaPlayer.seekTo(seekBar.getProgress());//停止拖拽时进度条的进度
        guideVdProgressTime.setText(String.valueOf(msConvertToMinute(seekBar.getProgress())));
    }


    public String msConvertToMinute(int ms) {
        String partA;
        String partB;
        int totalsecond=ms/1000;
        int minute=totalsecond/60;
        int second=totalsecond-minute*60;
        if (minute<10) {
            partA="0"+minute;
        }
        else {
            partA=String.valueOf(minute);
        }
        if (second<10) {
            partB="0"+second;
        }
        else {
            partB=String.valueOf(second);
        }
        return (partA+":"+partB);
    }


    private void loading(boolean show){
        animationDrawable = (AnimationDrawable) loadingImg.getBackground();
        if (show){
            loadingImg.setVisibility(VISIBLE);
            animationDrawable.start();//开启动画
        }else{
            loadingImg.setVisibility(GONE);
            animationDrawable.stop();//开启动画
        }
    }

    private void isPlayer(boolean p){

        if (p){
            if (isWifi()){
                guideVdStart.setBackgroundResource(R.mipmap.videoplayer_play1);
                guideVdProgressLl.setVisibility(GONE);
                guideVdStart.setVisibility(GONE);
            }else{
                guideVdStart.setBackgroundResource(R.mipmap.videoplayer_play1);
                guideVdProgressLl.setVisibility(GONE);
                guideVdLl.setVisibility(GONE);
            }
        }else{
            if (isWifi()){
                guideVdStart.setBackgroundResource(R.mipmap.videoplayer_pause1);
                guideVdLl.setVisibility(GONE);
            }else{
                guideVdStart.setVisibility(GONE);
                guideVdLl.setVisibility(VISIBLE);
            }
        }

    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            guideVdProgressLl.setVisibility(GONE);
            guideVdStart.setVisibility(GONE);
        }
    };

    public void setP(int p) {
        this.p = p;
    }

    public void setVideoUrl(String videoUrl) {
        this.videoUrl = videoUrl;
    }

    //初始化播放器
    public void initSurface(boolean change){
        loading(true);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnErrorListener(this);
        mediaPlayer.setOnVideoSizeChangedListener(this);
        surfaceHolder = guideVdSv.getHolder();
        //noinspection deprecation
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        guideVdProgressSeek.setOnSeekBarChangeListener(this);
        surfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder holder) {
                if (p > 0) {//�����¼�������в��Ž��ȡ�
                    try {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(videoUrl);
                        mediaPlayer.setDisplay(holder);
                        mediaPlayer.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    try {
                        mediaPlayer.setDataSource(videoUrl);
                        mediaPlayer.setDisplay(holder);
                        mediaPlayer.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
                if (mediaPlayer != null) {
                    p = mediaPlayer.getCurrentPosition();//��ǰ����λ��
                    mediaPlayer.stop();
                    timer.cancel();
                    task.cancel();
                    timer = null;
                    task = null;
                }
            }
        });
        if (change){
            try {
                mediaPlayer.reset();
                mediaPlayer.setDataSource(videoUrl);
                mediaPlayer.setDisplay(surfaceHolder);
                mediaPlayer.prepareAsync();
            } catch (IOException e) {
                ALog.e(e.getMessage());
                e.printStackTrace();
            }
        }

    }

    //重置播放器
    public void reset(){
        isPlayer(false);
        guideVdProgressLl.setVisibility(GONE);
        guideVdStart.setVisibility(GONE);
        p = 0;//��ǰ����λ��
        if (mediaPlayer!=null){
            mediaPlayer.stop();
            mediaPlayer.reset();
            mediaPlayer = null;
        }
        if (timer!=null){
            timer.cancel();
            timer = null;
        }
        if (task!=null) {
            task.cancel();
            task = null;
        }
    }

    //准备初始化
    public void initPrepare(){
        try {
            mediaPlayer.setDataSource(videoUrl);
            mediaPlayer.setDisplay(surfaceHolder);//****************
            mediaPlayer.prepareAsync();//
        } catch (IOException e) {
            e.printStackTrace();
            loading(false);
        }
        loading(true);
    }

    //清楚内存资源
    public void clear(){
        reset();
        if (animationDrawable != null) {
            if (animationDrawable.isRunning()) {
                animationDrawable.stop();
            }
            animationDrawable = null;
        }
    }

    public boolean isWifi() {
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo == null) {
            //无网络
            return false;
        }
        if(activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            //wifi
            ALog.e("wifi");
            return true;
        } else {
            //非wifi
            ALog.e("非wifi");
            return false;
        }
    }

    @Override
    public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
        int videoWidth = mediaPlayer.getVideoWidth();
        int videoHeight = mediaPlayer.getVideoHeight();

        ALog.e(this.getClass().getSimpleName()+"->videoWidth："+videoWidth);
        ALog.e(this.getClass().getSimpleName()+"->videoHeight："+videoHeight);

        int surfaceWidth = guideVdRl.getWidth();
        int surfaceHeight = guideVdRl.getHeight();

        //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
        float max;
        if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            //竖屏模式下按视频宽度计算放大倍数值
            max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
        } else {
            //横屏模式下按视频高度计算放大倍数值
            max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
        }

        //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
        videoWidth = (int) Math.ceil((float) videoWidth / max);
        videoHeight = (int) Math.ceil((float) videoHeight / max);

        //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
        params.addRule(RelativeLayout.CENTER_IN_PARENT, guideSvRl.getId());
        guideVdSv.setLayoutParams(params);
    }
}
